/**
 * API 数据服务 - 使用后端 API 替代 localStorage
 */
import { studentService } from '../../../../packages/shared/src/services/studentService';
import { classService } from '../../../../packages/shared/src/services/classService';
import { teacherService } from '../../../../packages/shared/src/services/teacherService';
import { dormitoryServiceApi } from '../../../../packages/shared/src/services/dormitoryService';
import { gradeService } from '../../../../packages/shared/src/services/gradeService';
import { attendanceService } from '../../../../packages/shared/src/services/attendanceService';

/**
 * API 数据服务类 - 连接后端接口
 */
export class ApiDataService {
  // 变更订阅回调
  private changeSubscribers: Array<(entityType: string, changeType: string, entityId: string) => void> = [];

  // 订阅数据变更
  subscribeToChanges(callback: (entityType: string, changeType: string, entityId: string) => void) {
    this.changeSubscribers.push(callback);
    return () => {
      this.changeSubscribers = this.changeSubscribers.filter(cb => cb !== callback);
    };
  }

  // 触发数据变更通知
  private notifyChange(entityType: string, changeType: string, entityId: string) {
    for (const callback of this.changeSubscribers) {
      try {
        callback(entityType, changeType, entityId);
      } catch (error) {
        console.error('Error in change subscriber:', error);
      }
    }
  }

  // ===== 学生相关方法 =====
  async getStudents(params?: any) {
    const result = await studentService.getStudents(params);
    // getStudents 现在返回 {list, total} 格式
    return Array.isArray(result) ? result : (result?.list || []);
  }

  async getStudentById(id: string) {
    return await studentService.getStudentById(id);
  }

  async createStudent(data: any) {
    const result = await studentService.createStudent(data);
    this.notifyChange('student', 'create', result.id || result._id);
    return result;
  }

  async updateStudent(id: string, data: any) {
    const result = await studentService.updateStudent(id, data);
    this.notifyChange('student', 'update', id);
    return result;
  }

  async deleteStudent(id: string) {
    await studentService.deleteStudent(id);
    this.notifyChange('student', 'delete', id);
  }

  // ===== 班级相关方法 =====
  async getClasses(params?: any) {
    const result = await classService.getClasses(params);
    // 确保返回数组
    return Array.isArray(result) ? result : [];
  }

  async getClassById(id: string) {
    return await classService.getClassById(id);
  }

  async createClass(data: any) {
    const result = await classService.createClass(data);
    this.notifyChange('class', 'create', result.id || result._id);
    return result;
  }

  async updateClass(id: string, data: any) {
    const result = await classService.updateClass(id, data);
    this.notifyChange('class', 'update', id);
    return result;
  }

  async deleteClass(id: string) {
    await classService.deleteClass(id);
    this.notifyChange('class', 'delete', id);
  }

  // ===== 教师相关方法 =====
  async getTeachers(params?: any) {
    const result = await teacherService.getTeachers(params);
    // getTeachers 现在返回 {list, total} 格式
    return Array.isArray(result) ? result : (result?.list || []);
  }

  async getTeacherById(id: string) {
    return await teacherService.getTeacherById(id);
  }

  async createTeacher(data: any) {
    const result = await teacherService.createTeacher(data);
    this.notifyChange('teacher', 'create', result.id || result._id);
    return result;
  }

  async updateTeacher(id: string, data: any) {
    const result = await teacherService.updateTeacher(id, data);
    this.notifyChange('teacher', 'update', id);
    return result;
  }

  async deleteTeacher(id: string) {
    await teacherService.deleteTeacher(id);
    this.notifyChange('teacher', 'delete', id);
  }

  // ===== 宿舍相关方法 =====
  async getDormitories(params?: any) {
    const result = await dormitoryServiceApi.getDormitories(params);
    // 确保返回数组，并处理 _id 转 id
    const data = result?.list || result || [];
    if (Array.isArray(data)) {
      return data.map((dorm: any) => ({
        ...dorm,
        id: dorm._id || dorm.id,
      }));
    }
    return [];
  }

  async getDormitoryById(id: string) {
    return await dormitoryServiceApi.getDormitory(id);
  }

  async createDormitory(data: any) {
    const result = await dormitoryServiceApi.createDormitory(data);
    this.notifyChange('dormitory', 'create', result.id || result._id);
    return result;
  }

  async updateDormitory(id: string, data: any) {
    const result = await dormitoryServiceApi.updateDormitory(id, data);
    this.notifyChange('dormitory', 'update', id);
    return result;
  }

  async deleteDormitory(id: string) {
    await dormitoryServiceApi.deleteDormitory(id);
    this.notifyChange('dormitory', 'delete', id);
  }

  async getBuildings() {
    return await dormitoryServiceApi.getBuildings();
  }

  // ===== 成绩相关方法 =====
  async getGrades(params?: any) {
    const result = await gradeService.getGrades(params);
    // getGrades 现在返回 {list, total} 格式
    return Array.isArray(result) ? result : (result?.list || []);
  }

  async getGradesByStudentId(studentId: string) {
    return await gradeService.getGradesByStudentId(studentId);
  }

  async createGrade(data: any) {
    const result = await gradeService.createGrade(data);
    this.notifyChange('grade', 'create', result.id || result._id);
    return result;
  }

  // ===== 考勤相关方法 =====
  async getAttendances(params?: any) {
    const result = await attendanceService.getAttendances(params);
    // getAttendances 现在返回 {list, total} 格式
    return Array.isArray(result) ? result : (result?.list || []);
  }

  async getAttendancesByStudentId(studentId: string) {
    return await attendanceService.getAttendancesByStudentId(studentId);
  }

  async getAttendancesByClassId(classId: string) {
    return await attendanceService.getAttendancesByClassId(classId);
  }

  async createAttendance(data: any) {
    const result = await attendanceService.createAttendance(data);
    this.notifyChange('attendance', 'create', result.id || result._id);
    return result;
  }

  // ===== 审计日志相关方法 =====
  async getAuditLogs() {
    // 后端暂时可能没有审计日志接口，返回空数组
    return [];
  }

  // ===== 数据验证 =====
  async validateAllData() {
    // 简化版本，后端已经保证数据一致性
    return { isValid: true, errors: [] };
  }
}

// 导出单例
export const apiDataService = new ApiDataService();

